#include <iostream>
#include <json/json.h>
#include <sstream>
#include <memory>

bool Serialize(const Json::Value &val, std::string& dst){
    Json::StreamWriterBuilder swb;
    swb.settings_["emitUTF8"] = true;

    // 构造对象
    std::unique_ptr<Json::StreamWriter> sw(swb.newStreamWriter());
    // auto sw = std::make_unique<Json::StreamWriter>(swb.newStreamWriter());
    std::stringstream ss;
    if(sw->write(val, &ss) != 0){
        std::cout << "Json 序列化失败 \n";
        return false;
    }
    dst = ss.str();
    return true;
}

bool UnSerialize(Json::Value &val, const std::string& src){
    Json::CharReaderBuilder crb;
    std::unique_ptr<Json::CharReader> cr(crb.newCharReader());
    // auto cr = std::make_unique<Json::CharReader>(crb.newCharReader());
    std::string err;
    if(!cr->parse(src.c_str(), src.c_str() + src.size(), &val, &err)){
        std::cout << "Json 反序列化失败: " << err << std::endl; 
        return false;
    }
    return true;
}


int main(){
    Json::Value stu;
    stu["姓名"] = "张三"; stu["年龄"] = 18;
    stu["成绩"].append(78); stu["成绩"].append(99); stu["成绩"].append(89); 
    
    std::string str;
    if(!Serialize(stu, str)){
        return -1;
    }
    std::cout << str << std::endl;

    Json::Value val;
    if(!UnSerialize(val, str)){
        return -1;
    }

    std::cout << val["姓名"].asString() << std::endl;
    std::cout << val["年龄"].asInt() << std::endl;
    int sz = val["成绩"].size();
    for (int i = 0; i < sz; i++) {
        std::cout << val["成绩"][i].asFloat() << std::endl;
    }

    return 0;
}